package com.example.pixelyear.utils;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.net.Network;
import android.net.NetworkInfo;
import android.os.Build;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.KeyCharacterMap;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.WindowManager;
import android.widget.Toast;

import com.example.pixelyear.MyApp;
import com.example.pixelyear.R;
import com.socks.library.KLog;

import java.io.*;
import java.lang.reflect.Field;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
import java.util.TimeZone;


public class Utils {

    /**
     * 没有连接网络
     */
    public static final int NETWORK_NONE   = -1;
    /**
     * 移动网络
     */
    public static final int NETWORK_MOBILE = 0;
    /**
     * 无线网络
     */
    public static final int NETWORK_WIFI   = 1;

    private static Toast toast = null;

    public static void showToast(String msg) {
        if (toast == null)
            toast = Toast.makeText(MyApp.getContext(), msg, Toast.LENGTH_SHORT);
        else
            toast.setText(msg);
        toast.show();
    }

    /**
     * 获取显示指标
     *
     * @param context 上下文
     * @return DsisplayMetrics
     */
    private static DisplayMetrics getDisplayMetrics(Context context) {
        if (context instanceof Activity) {
            Activity activity = (Activity) context;
            if (!activity.isDestroyed()) {
                WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
                Display display = windowManager.getDefaultDisplay();
                DisplayMetrics displayMetrics = new DisplayMetrics();
                display.getMetrics(displayMetrics);
                return displayMetrics;
            } else
                return null;
        } else {
            WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
            Display display = windowManager.getDefaultDisplay();
            DisplayMetrics displayMetrics = new DisplayMetrics();
            display.getMetrics(displayMetrics);
            return displayMetrics;
        }
    }

    /**
     * 获取屏幕的宽度
     *
     * @param context 上下文
     * @return WindowWidth
     */
    public static int getWindowWidth(Context context) {
        DisplayMetrics displayMetrics = getDisplayMetrics(context);
        if (displayMetrics != null)
            return displayMetrics.widthPixels;
        else
            return 0;
    }

    /**
     * 获取屏幕的高度
     *
     * @param context 上下文
     * @return WindowHeight
     */
    public static int getWindowHeight(Context context) {
        DisplayMetrics displayMetrics = getDisplayMetrics(context);
        if (displayMetrics != null)
            return displayMetrics.heightPixels;
        else
            return 0;
    }


    /**
     * 获取状态栏高度
     *
     * @param context
     * @return
     */
    public static int getStatusBarHeight(Context context) {
        Class<?> c = null;
        Object obj = null;
        Field field = null;
        int x = 0, sbar = 0;
        try {
            c = Class.forName("com.android.internal.R$dimen");
            obj = c.newInstance();
            field = c.getField("status_bar_height");
            x = Integer.parseInt(field.get(obj).toString());
            sbar = context.getResources().getDimensionPixelSize(x);
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        return sbar;
    }

    public static int getYear() {
        return NumberUtils.parseInt(FormatTime(getNowTime(), "yyyy", false));
    }

    public static int getMonth() {
        return NumberUtils.parseInt(FormatTime(getNowTime(), "MM", false));
    }

    public static int getDay() {
        return NumberUtils.parseInt(FormatTime(getNowTime(), "dd", false));
    }

    /**
     * 时间
     *
     * @param time 为 yyyy-MM-dd格式
     * @return 返回星期
     */
    public static int dateTranslateWeek(String time) {
        SimpleDateFormat year = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat week = new SimpleDateFormat("E");
        Date d = null;
        try {
            d = year.parse(time);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        if (d == null)
            return 0;
        else
            return NumberUtils.translateWeek(week.format(d));
    }

    /**
     * 格式化时间
     *
     * @param time 时间
     * @return 格式化后的时间
     */
    public static String FormatTime(long time) {
        return FormatTime(time, "HH:mm:ss", false);
    }

    /**
     * 格式化时间，自带格式
     *
     * @param time       时间
     * @param fm         时间格式
     * @param isneedZone 是否需要 区
     * @return 格式化后的时间
     */
    public static String FormatTime(long time, String fm, boolean isneedZone) {
        SimpleDateFormat format = new SimpleDateFormat(fm);
        if (isneedZone)
            format.setTimeZone(TimeZone.getTimeZone("GMT+0"));
        return format.format(new Date(time));
    }


    public static int getRandColorCode() {
        String r, g, b;
        Random random = new Random();
        r = Integer.toHexString(random.nextInt(256)).toUpperCase();
        g = Integer.toHexString(random.nextInt(256)).toUpperCase();
        b = Integer.toHexString(random.nextInt(256)).toUpperCase();

        r = r.length() == 1 ? "0" + r : r;
        g = g.length() == 1 ? "0" + g : g;
        b = b.length() == 1 ? "0" + b : b;
        KLog.e("yxs", "生成的颜色：" + r + g + b);
        return Color.parseColor("#" + r + g + b);
    }


    private static long lastClickTime;

    /**
     * 用来防止复点击的方法
     *
     * @return
     */
    public static boolean isFastDoubleClick() {
        long time = System.currentTimeMillis();
        long timeD = time - lastClickTime;
        if (0 < timeD && timeD < 500) {
            return true;
        }
        lastClickTime = time;
        return false;
    }

    /**
     * 判断颜色深浅
     *
     * @param color 颜色
     * @return 返回黑色或者白色
     */
    public static int colorDepth(int color) {
        float[] hsv = new float[3];
        Color.colorToHSV(color, hsv);
        double c = hsv[0] * 0.299 + hsv[1] * 0.587 + hsv[2] * 0.114;
        if (c > 90 || c == 0) {
            return UIUtils.getColor(R.color.white);
        } else
            return UIUtils.getColor(R.color.black);
    }


    /**
     * 文件复制.
     */
    public static boolean copy(String srcFile, String destFile) {
        try {
            FileInputStream in = new FileInputStream(srcFile);
            FileOutputStream out = new FileOutputStream(destFile);
            byte[] bytes = new byte[1024];
            int c;
            while ((c = in.read(bytes)) != -1) {
                out.write(bytes, 0, c);
            }
            in.close();
            out.flush();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * 从InputStream流复制文件.
     */
    public static long copy(InputStream from, File to) throws IOException {
        long totalBytes = 0;
        FileOutputStream fos = new FileOutputStream(to, false);
        try {
            if (!to.exists())
                to.createNewFile();
            byte[] data = new byte[1024];
            int len;
            while ((len = from.read(data)) > -1) {
                fos.write(data, 0, len);
                totalBytes += len;
            }
            fos.flush();
        } finally {
            fos.close();
        }
        return totalBytes;
    }

    public static void writeText(String text, File file) {
        try {
            if (!file.exists()) {
                file.createNewFile();
            }
            PrintWriter outputStream = new PrintWriter(new FileOutputStream(file));
            outputStream.print(text);
            outputStream.flush();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     * InputStream转换String
     *
     * @param inputStream
     * @return
     */
    public static String parsingInput(InputStream inputStream) {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        try {
            byte[] bytes = new byte[1024];
            int len = 0;
            while ((len = inputStream.read(bytes)) != -1) {
                byteArrayOutputStream.write(bytes, 0, len);
            }
        } catch (IOException e) {
            return "";
        }
        return byteArrayOutputStream.toString();
    }


    //重启App
    public static void ReStartApp(final Context context, final Class<?> clazz) {
        DefaultHandler.getInstance().postDelayed(new Runnable() {
            @Override
            public void run() {
                Intent intent = new Intent(context, clazz);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(intent);
                ActivityListUtils.getInstance().finishAllActivity();
                android.os.Process.killProcess(android.os.Process.myPid());
            }
        }, 1000);
    }

    private static long getNowTime() {
        return System.currentTimeMillis() - YxsSpUtils.INSTANCE.getLong(Constant.NOW_TIME, 0);
    }


    /**
     * 隐藏虚拟按键
     */
    public static void hideBottomUIMenu(Activity activity) {
        if (!checkDeviceHasNavigationBar(activity))
            return;
        if (Build.VERSION.SDK_INT > 11 && Build.VERSION.SDK_INT < 19) {
            View v = activity.getWindow().getDecorView();
            v.setSystemUiVisibility(View.GONE);
        } else if (Build.VERSION.SDK_INT >= 19) {
            View decorView = activity.getWindow().getDecorView();
            int uiOptions = View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION // hide nav bar
                    | View.SYSTEM_UI_FLAG_IMMERSIVE;
            decorView.setSystemUiVisibility(uiOptions);
        }
    }

    /**
     * 显示虚拟按键
     */
    public static void showBottomUIMenu(Activity activity) {
        if (!checkDeviceHasNavigationBar(activity))
            return;
        if (Build.VERSION.SDK_INT > 11 && Build.VERSION.SDK_INT < 19) {
            //低版本sdk
            View v = activity.getWindow().getDecorView();
            v.setSystemUiVisibility(View.VISIBLE);
        } else if (Build.VERSION.SDK_INT >= 19) {
            View decorView = activity.getWindow().getDecorView();
            int uiOptions =
                    View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                            | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION //这一句是关键，不加这一句，虚拟键盘弹出时将挤压布局
                            | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
            decorView.setSystemUiVisibility(uiOptions);
        }
    }

    /**
     * 获取是否有虚拟按键
     * 通过判断是否有物理返回键反向判断是否有虚拟按键
     *
     * @param context
     * @return
     */
    public static boolean checkDeviceHasNavigationBar(Context context) {

        boolean hasMenuKey = ViewConfiguration.get(context)
                .hasPermanentMenuKey();
        boolean hasBackKey = KeyCharacterMap
                .deviceHasKey(KeyEvent.KEYCODE_BACK);
        if (!hasMenuKey & !hasBackKey) {
            // 做任何你需要做的,这个设备有一个导航栏
            return true;
        }
        return false;
    }


    /**
     * 判断设备是否是手机
     *
     * @param context 上下文
     * @return {@code true}: 是<br>{@code false}: 否
     */
    public static boolean isPhone(Context context) {
        TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        return tm.getPhoneType() != TelephonyManager.PHONE_TYPE_NONE;
    }

    /**
     * 获取手机的IMIE
     * <p>需与{@link #isPhone(Context)}一起使用</p>
     * <p>需添加权限 {@code <uses-permission android:name="android.permission.READ_PHONE_STATE"/>}</p>
     *
     * @param context 上下文
     * @return IMIE码
     */
    @SuppressLint({"MissingPermission", "HardwareIds"})
    public static String getPhoneIMEI(Context context) {
        String deviceId;
        try {
            if (isPhone(context) && Build.VERSION.SDK_INT <= Build.VERSION_CODES.P) {
                TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
                deviceId = tm.getDeviceId();
            } else {
                deviceId = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
            }
        } catch (Exception e) {
            return "-1";
        }
        if (deviceId == null)
            deviceId = "-1";
        return deviceId;
    }

    /**
     * [获取应用程序版本名称信息]
     *
     * @param context
     * @return 当前应用的版本名称
     */
    public static synchronized String getVersionName(Context context) {
        try {
            PackageManager packageManager = context.getPackageManager();
            PackageInfo packageInfo = packageManager.getPackageInfo(
                    context.getPackageName(), 0);
            return packageInfo.versionName;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 获取网络状态
     * @param context
     *         上下文
     * @return 网络状态
     */
    public static int getNetState(Context context) {
        if (context instanceof Activity) {
            Activity activity = (Activity) context;
            if (activity.isDestroyed())
                return -1;
        } else if (context == null)
            return -1;
        // 得到连接管理器对象
        ConnectivityManager connectivityManager = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && !Build.BRAND.equals("vivo") && !isXiaoMi()) {
            for (Network network : connectivityManager.getAllNetworks()) {
                NetworkInfo networkInfo = connectivityManager.getNetworkInfo(network);
                if (networkInfo.getDetailedState().equals(NetworkInfo.DetailedState.CONNECTED)) {
                    if (!networkInfo.getSubtypeName().isEmpty())
                        return NETWORK_MOBILE;
                    else
                        return NETWORK_WIFI;
                }
            }
        } else {
            NetworkInfo activeNetworkInfo = connectivityManager
                    .getActiveNetworkInfo();
            if (activeNetworkInfo != null && activeNetworkInfo.isConnected()) {
                if (activeNetworkInfo.getType() == (ConnectivityManager.TYPE_WIFI)) {
                    return NETWORK_WIFI;
                } else if (activeNetworkInfo.getType() == (ConnectivityManager.TYPE_MOBILE)) {
                    return NETWORK_MOBILE;
                }
            } else {
                return NETWORK_NONE;
            }
        }
        return NETWORK_NONE;
    }

    public static boolean isXiaoMi() {
        return "Xiaomi".equals(Build.MANUFACTURER);
    }

}